<!-- 团购列表 
    从分页组件传了两个事件过来pageChange
-->
<template>
    <div class="main" @scroll.passive="scrollTop($event)">
          <!-- 团购搜索头部 -->
        <div class="croupPurchase-top">
            <el-space wrap :size="10">
                <el-input v-model="croupPurchase.title" placeholder="请输入商品名称" clearable />
                <el-input v-model="croupPurchase.id" placeholder="请输入团购ID" clearable />
                <el-select v-model="croupPurchase.status" placeholder="请选择用户状态" @clear="croupPurchase.status=undefined"
                    clearable>
                    <el-option label="冻结" :value="0">冻结</el-option>
                    <el-option label="激活" :value="1">激活</el-option>
                    <el-option label="全部" value="">全部</el-option>
                </el-select>
                <el-button type="primary" :icon="Search" @click="handlrSearch">查找</el-button>
                <el-button type="primary" :icon="Plus" @click="handlrAdd">添加</el-button>
            </el-space>
        </div>
        <!-- 团购列表 -->
        <div class="croupPurchase-table">
            <el-table :data="tableData" border style="width: 100%;">
                <el-table-column type="expand">
                    <template #default="scope">
                        <el-descriptions :column="1" border>
                            <el-descriptions-item label="类目ID" label-align="left" class-name="my-content" width="150px">
                                <span>{{scope.row.categoryId}}</span>
                            </el-descriptions-item>
                            <!-- 商品sku列表 -->
                            <el-descriptions-item label="商品sku属性" label-align="left" align="center"
                                label-class-name="my-label" class-name="my-content" width="150px">
                                <el-table :data="groupPurchaseList" border style="width: 100%;">
                                    <el-table-column prop="id" label="SkuId" align="center" />
                                    <el-table-column prop="title" label="规格标题" align="center" />
                                    <el-table-column prop="skuGroupShopPrice" label="团购价格(元)" align="center" />
                                    <el-table-column prop="stock" label="库存" align="center">
                                        <template #default="scope">
                                            <span>{{scope.row.stock}}(件)</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="originalPrice" label="原始价格(元)" align="center" />
                                    <el-table-column prop="price" label="售卖价格(元)" align="center" />
                                    <el-table-column prop="vipPrice" label="会员价格(元)" align="center" />
                                    <el-table-column prop="barCode" label="国际条码" align="center" />
                                </el-table>
                            </el-descriptions-item>
                        </el-descriptions>
                    </template>
                </el-table-column>
                <el-table-column prop="id" label="团购ID" align="center" width='100' />
                <el-table-column prop="spuId" label="商品ID" align="center" width='80' />
                <el-table-column prop="title" label="商品名称" align="center" width='500' />
                <el-table-column prop="img" label="商品主图" align="center" width='150'>
                    <template #default="scope">
                        <el-popover width="300px" placement="right" :popper-style="'background-color:'+scope.row.color">
                            <template #reference>
                                <el-image style="width: 100px;height: 50px;" :src="scope.row.img" fit="contain" />
                            </template>
                            <template #default>
                                <div style="display: flex;justify-content: center;">
                                    <el-image style="width: 100%; height: 100%" :src="scope.row.img" />
                                </div>
                            </template>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="automaticRefund" label="未满策略" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.automaticRefund==0?'warning':'success'">
                            {{scope.row.automaticRefund==0?'发货':'退款'}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="活动状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status==0?'danger':''">{{scope.row.status==0?'冻结':'激活'}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="gmtStart" label="开始时间" align="center" width="180">
                    <template #default="scope">
                        <template v-if="scope.row.gmtStart">
                            {{new Date(scope.row.gmtStart).formate('yyyy-MM-dd hh:mm:ss')}}
                        </template>
                        <template v-else>
                            <span>无</span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="gmtEnd" label="结束时间" align="center" width="180">
                    <template #default="scope">
                        <template v-if="scope.row.gmtEnd">
                            {{new Date(scope.row.gmtEnd).formate('yyyy-MM-dd hh:mm:ss')}}
                        </template>
                        <template v-else>
                            <span>无</span>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column prop="buyerNum" label="当前人数" align="center" />
                <el-table-column prop="minNum" label="目标人数" align="center" />
                <el-table-column label="操作" align="center" width="200">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加弹出框 -->
            <el-drawer v-model="visible" :show-close="false" direction="ltr" :size="800">
                <template #header="{ close, titleId, titleClass }">
                    <h4 :id="titleId" :class="titleClass">创建团购商品</h4>
                    <el-button @click="visible=false">取消</el-button>
                    <el-button type="primary" @click="hedlerCreate">{{bool==true?'创建':'编辑'}}</el-button>
                </template>
                <div class="commodity-sku">
                    <h4>商品属性(spu)</h4>
                    <el-form ref="ruleFormRef" :model="form" require-asterisk-position="left" class="demo-ruleForm"
                        status-icon :rules="rules" label-position="left">
                        <el-form-item label="团购商品" placeholder="团购商品" prop="groupShopSkuList" label-width="150px">
                            <el-cascader :options="options" :props="props" v-model='form.spuId'
                                @change="lodeGroupShopSkuList" clearable />
                        </el-form-item>
                        <el-form-item label="团购时间" prop="title" label-width="150px">
                            <el-date-picker v-model="form.gmtStart" type="datetime" placeholder="选择日期"
                                format="YYYY/MM/DD HH:mm:ss" value-format="x" clearable />
                            <span>至</span>
                            <el-date-picker v-model="form.gmtEnd" type="datetime" placeholder="选择日期"
                                format="YYYY/MM/DD HH:mm:ss" value-format="x" clearable />
                        </el-form-item>
                        <el-form-item label="团购基础人数" prop="type" label-width="150px">
                            <el-input-number v-model="form.minNum" class="mx-4" :min="1" controls-position="right"
                                clearable />
                        </el-form-item>
                        <el-form-item label="活动结束时人数没有" label-width="150px">
                            <el-radio-group v-model="form.automaticRefund">
                                <el-radio-button  :label="0" > 不退货,我要发货</el-radio-button>
                                <el-radio-button  :label="1" >自动退货,我不发货</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="达到基础人数采取:" />
                    </el-form>
                </div>
                <div class="commodity-type">
                    <h4>商品类型(spu)</h4>
                    <el-popover v-model:visible="visibles" width="400px" placement="right" trigger="click">
                        <template #reference>
                            <el-button type="primary" plain :disabled="groupShopSkuList.length==0">批量定价
                            </el-button>
                        </template>
                        <template #default>
                            <div style="display: flex;align-items: center;padding: 0px 30px;">
                                <div>团购价格</div>
                                <el-input-number v-model="num" :min="1" controls-position="right"
                                    style="margin-left: 33px;margin-right: 5px;" />元
                            </div>
                            <div style="text-align: center;margin: 20px 0px;">
                                <el-button @click="visibles=false">取消</el-button>
                                <el-button type="primary" @click="hedlerCommodityprimary">确定</el-button>
                            </div>
                        </template>
                    </el-popover>
                </div>
                <!-- 添加sku列表 -->
                <div class="groupShopSkuList">
                    <el-table :data="groupShopSkuList" style="width: 100%">
                        <el-table-column prop="id" label="skuID" align="center" width="80" />
                        <el-table-column prop="barCode" label="sku条形码" align="center" width="150" />
                        <el-table-column prop="title" label="类型名" align="center" width="150" />
                        <el-table-column prop="stock" label="库存" align="center" />
                        <el-table-column prop="price" label="现价/元" align="center" />
                        <el-table-column prop="skuGroupShopPrice" label="团购价格/元" align="center" />
                        <el-table-column label="操作" align="center">
                            <template #default="scope">
                                <el-button type="primary" @click="toUpdate(scope.$index,scope.row)">更新</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 更新弹出框 -->
                    <el-dialog v-model="dialogFormVisible" title="更新团购价格">
                        <el-form :model="toUpdateList" require-asterisk-position="left" label-position="left">
                            <el-form-item label="团购价格" label-width="140px">
                                <el-input-number v-model="toUpdateList.singleGgroupPurchaseprice" class="mx-4" :min="1"
                                    controls-position="right" clearable />元
                            </el-form-item>
                            <el-form-item label="现价" label-width="140px">
                                <span>{{toUpdateList.presentPrice}}元</span>
                            </el-form-item>
                            <el-form-item label="sku类型名" label-width="140px">
                                <span>{{ toUpdateList.skuTypeName}}</span>
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <span class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="updateOk">确定</el-button>
                            </span>
                        </template>
                    </el-dialog>
                </div>
            </el-drawer>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main" :visibility-height="0" v-if="bool" />
    </div>
</template>
<script  setup lang="ts">
import { nextTick, reactive, ref, watch } from 'vue'
import { Search, Plus, } from '@element-plus/icons-vue'
import { get, post } from "@/utils/request";
import { ClassPagination } from "#/index";
import Paging from "@/components/paging/Paging.vue";
import "@/utils/dataFriend"
import { ElButton, ElDrawer } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
//分页数据
let pagingDatas = reactive(new ClassPagination())
const options: TypeAdOptions[] = reactive([]) //商品列表
let rollHeight = ref(0)  //滚动距离
let num = ref(1)
let main = ref()  //滚动组件对象的引用
const dialogFormVisible = ref(false)
let visible = ref(false) //对话框的显示隐藏
let visibles = ref(false) //更新对话框的显示隐藏
let groupShopSkuList: TypeGroupPurchaseList[] = reactive([]) //团购sku数据
let tableData: TypeCroupPurchase[] = reactive([]) //团购列表数据
let bool = ref(true)  //用来判断滚动组件的显示隐藏
let groupPurchaseList: TypeGroupPurchaseList[] = reactive([])//团购商品数据
let croupPurchase = reactive({
    title: '',
    id: '',
    status: undefined,
})
const props = {
    emitPath: false,
    value: 'id',
    label: 'label',
    children: 'children',
}
//更新单个团购数据
let toUpdateList:TypeToUpdateList =reactive({
    singleGgroupPurchaseprice:"",
    presentPrice:"",
    skuTypeName:"",
    index:0,
})
//添加对话框数据
let form = reactive({
    spuId: '',
    gmtStart: '',
    gmtEnd: '',
    minNum : 1,
    automaticRefund:0,
    id:'',
})
//商品列表
function lodeCommodityTree() {
    if (options.length == 0) {
        post({ _gp: 'admin.product', _mt: 'getSpuBigTree' }).then((res) => {
            console.log(res)
            if (200 == res.errno) {
                options.length = 0
                options.push(...res.data)
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    }
}
lodeCommodityTree()
//商品sku列表
function lodeGroupShopSkuList() {
    console.log(form.spuId)
    let data = {
        _gp:'admin.product',
        _mt:'detail',
        spuId:form.spuId
    }
    post(data).then((res) => {
        console.log(res)
        if (200 == res.errno) {
            groupShopSkuList.length = 0
            groupShopSkuList.push(...res.data.skuList)
            groupShopSkuList.forEach((item: { skuId: number; id: number }) => {
                item.skuId = item.id;
             });
        } else {
            ElMessage.error(res.errmsg)
        }
    })
}


//弹出框验证
const validateTitle = (rule: object, value: string, callback: Function) => {
    if ('' === value) {
        return callback(new Error('内容不能为空'))
    } else {
        callback()
    }
}
//失焦触发验证
const rules = reactive({
    title: [{ validator: validateTitle, trigger: 'blur' }],
    type: [{ validator: validateTitle, trigger: ['blur', 'change'] }],
    status: [{ validator: validateTitle, trigger: 'blur' }],
    unionType: [{ validator: validateTitle, trigger: ['blur', 'change'] }],
    unionValue: [{ validator: validateTitle, trigger: ['blur', 'change'] }]
})

let newCroupPurchase = { ...croupPurchase }
//加载团购列表
function lodeCroupPurchaseList() {
    let data = {
        _gp: 'admin.groupshop',
        _mt: "list",
        id: newCroupPurchase.id,
        spuName: newCroupPurchase.title,
        status: newCroupPurchase.status,
        page: pagingDatas.page,
        limit: pagingDatas.limit
    }
    get(data).then((res) => {
        // console.log(res)
        if (200 == res.errno) {
            tableData.length = 0
            groupPurchaseList.length = 0,
            tableData.push(...res.data.items)
            pagingDatas.total = res.data.total
            tableData.forEach(item => {
               groupPurchaseList.push(...item.groupShopSkuDTOList)
            })
        }else{
            ElMessage.error(res.errmsg)
        }
    })
}

//团购sku数据添加合并一个属性
function hedlerCommodityprimary() {
    groupShopSkuList.map(item => Object.assign(item, { skuGroupShopPrice: num.value }))
    visibles.value = false
}
//更新对话框
function toUpdate(index:number,row: TypeGroupPurchaseList) {
    dialogFormVisible.value = true,
    toUpdateList.singleGgroupPurchaseprice = row.skuGroupShopPrice
    toUpdateList.presentPrice = row.price
    toUpdateList.skuTypeName = row.title
    toUpdateList.index = index
}
//更新单个团购价格
function updateOk() {
    groupShopSkuList[toUpdateList.index].skuGroupShopPrice =  toUpdateList.singleGgroupPurchaseprice 
    dialogFormVisible.value = false
}
//查找
function handlrSearch() {
    Object.assign(newCroupPurchase, croupPurchase)
    lodeCroupPurchaseList()
}
//添加
let newForm = { ...form }
function handlrAdd() {
    visible.value = true
    bool.value = true
    Object.assign(form, newForm)
    groupShopSkuList.length = 0
}

//创建
function hedlerCreate() {
   let groupShopList = JSON.stringify(groupShopSkuList)
    let data = {
        _gp:'admin.groupshop',
        _mt:form.id==''?'create':'edit',
      ...form,
      groupShopSkuList:groupShopList,
    }
   post(data).then((res)=>{
      if(200==res.errno){
        visible.value = false
        ElMessage.success(form.id==""?"创建成功":"编辑成功")
        lodeCroupPurchaseList()
      }else{
        ElMessage.error(res.errmsg)
      }
   })
}
//修改
function handleEdit(row: TypeCroupPurchase) {
    console.log(row)
    bool.value =false
    visible.value = true
    Object.assign(form,row)
    groupShopSkuList.length = 0
    groupShopSkuList.push(...row.groupShopSkuDTOList)
    // console.log(groupShopSkuList)
}
//删除
function handleDelete(row: TypeCroupPurchase) {
    let data = {
        _gp: 'admin.groupshop',
        _mt: 'delete',
        id: row.id,
    }
    ElMessageBox.confirm(
        '请问是否删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
        }
    ).then(() => {
        get(data).then((res) => {
            if (200 == res.errno) {
                ElMessage.success("删除成功")
                lodeCroupPurchaseList()
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    })
        .catch(() => {
            ElMessage.info("取消操作")
        })
}
//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    lodeCroupPurchaseList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}
//滚动事件
let scrollTop = (e: Event) => {
    rollHeight.value = Math.floor((e.target as EventTarget).scrollTop)
}
//监听滚动的距离
watch(rollHeight, (val: number) => {
    //    console.log(val);
    bool.value = val > 60
})

lodeCroupPurchaseList()

</script>
<style scoped lang="less">
.croupPurchase-top {
    margin: 15px 0px;

    .el-input {
        width: 11vw;
    }
}

.croupPurchase-table {
    /deep/ .el-drawer__body {
        padding: 0px;

        .commodity-sku {
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;

            .el-form {
                margin-top: 20px;

                .el-form-item__label {
                    margin-left: 40px;
                }
            }
        }

        .commodity-type {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid #ccc;

            /deep/ .commodity-primary {
                margin-bottom: 20px !important;
            }
        }

        .groupShopSkuList {
            padding: 10px;
            .el-dialog{
                .el-form{
                    .el-form-item__label{
                        margin-left: 50px;
                    }
                }
            }
        }
    }

}
</style>